package com.bawei.module_live.ui.view

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View

class RedCircleCountDownView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : View(context, attrs) {

    private var progress = 1f // 1f~0f
    var text: String = ""
        private set
    private val paintCircle = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = Color.parseColor("#FF3B30")
        style = Paint.Style.STROKE
        strokeWidth = 16f
    }
    private val paintText = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = Color.WHITE
        textSize = 80f
        textAlign = Paint.Align.CENTER
    }

    fun setProgress(progress: Float) {
        this.progress = progress
        invalidate()
    }

    fun setText(text: String) {
        this.text = text
        invalidate()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val ringStrokeWidth = dp2px(3f)
        val radius = width.coerceAtMost(height) / 2f - ringStrokeWidth

        val cx = width / 2f
        val cy = height / 2f

        // 1. 画白色实心圆
        val fillPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
            color = Color.WHITE
            style = Paint.Style.FILL
        }
        canvas.drawCircle(cx, cy, radius, fillPaint)

        // 2. 画金色圆环
        val ringPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
            color = Color.parseColor("#FFD700")
            style = Paint.Style.STROKE
            strokeWidth = ringStrokeWidth
            strokeCap = Paint.Cap.ROUND
        }
        val rect = RectF(
            cx - radius - ringStrokeWidth / 2,
            cy - radius - ringStrokeWidth / 2,
            cx + radius + ringStrokeWidth / 2,
            cy + radius + ringStrokeWidth / 2
        )
        canvas.drawArc(rect, -90f, 360f * progress, false, ringPaint)

        // 3. 画黑色细体文字
        val textPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
            color = Color.BLACK
            textSize = radius * 0.6f
            textAlign = Paint.Align.CENTER
        }
        val fm = textPaint.fontMetrics
        val baseLine = cy - (fm.ascent + fm.descent) / 2
        canvas.drawText(text, cx, baseLine, textPaint)
    }

    // 工具方法
    private fun dp2px(dp: Float): Float {
        return dp * resources.displayMetrics.density
    }
}